package com.stek.app;

import java.util.ArrayList;
import java.util.List;

import android.app.Dialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.PopupMenu.OnMenuItemClickListener;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.ads.AdView;
import com.stek.R;
import com.stek.app.AppListAdapter.OnInnerClickLisener;
import com.stek.base.BaseOverLayActivity;
import com.stek.db.DBHelper;
import com.stek.lib.pulltorefresh.library.ActionBarPullToRefresh;
import com.stek.lib.pulltorefresh.library.PullToRefreshLayout;
import com.stek.lib.pulltorefresh.library.listeners.OnRefreshListener;
import com.stek.model.AppInfo;
import com.stek.utils.AdMode;
import com.stek.utils.AppUtils;
import com.stek.utils.Broadcast;
import com.stek.utils.CONFIG;
import com.stek.utils.Logging;
import com.stericson.RootTools.RootTools;

public class AppActivity extends BaseOverLayActivity implements
		OnInnerClickLisener, OnItemClickListener,
		LoaderManager.LoaderCallbacks<List<AppInfo>>, OnRefreshListener {
	public static final String EXTRA_PICK_APP = "ACTION_PICK_APP";
	public static final String EXTRA_APP_POSITION = "EXTRA_APP_POSITION";
	private static final int MENU_ACTION_CONVERT_2_USER = 0;
	private static final int MENU_ACTION_CONVERT_2_SYSTEM = 1;
	private static final String USER_APP_PATH = "/data/app";
	private static final String SYSTEM_APP_PATH = "/system/app";
	private ArrayList<AppInfo> mApplicationInfos;
	private List<AppInfo> mOriginalAppInfos;
	private AppListAdapter mAppAdapter;
	private ListView mAppListView;
	private boolean isPickApp = false;
	private int appPosition = 0;
	private boolean isRoot;
	private AppLoader mAppLoader;
	private PullToRefreshLayout mPullToRefreshLayout;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_app);
		mAppListView = (ListView) findViewById(R.id.list);
		mApplicationInfos = new ArrayList<AppInfo>();
		mOriginalAppInfos = new ArrayList<AppInfo>();
		mAppAdapter = new AppListAdapter(getApplicationContext(),
				mApplicationInfos);
		mAppListView.setAdapter(mAppAdapter);
		mAppAdapter.setLisener(AppActivity.this);
		mAppListView.setOnItemClickListener(AppActivity.this);
		isPickApp = getIntent().getBooleanExtra(EXTRA_PICK_APP, false);
		appPosition = getIntent().getIntExtra(EXTRA_APP_POSITION, -1);
		new Thread(new Runnable() {

			@Override
			public void run() {
				isRoot = RootTools.isRootAvailable();
			}
		}).start();
		mPullToRefreshLayout = (PullToRefreshLayout) findViewById(R.id.prf);
		ActionBarPullToRefresh.from(this).theseChildrenArePullable(R.id.list)
				.listener(this).setup(mPullToRefreshLayout);
		getSupportLoaderManager().initLoader(0, null, this);
		// adView = (AdView) findViewById(R.id.admod);
		// AdMode.init(adView);
	}

	@Override
	protected void onNewIntent(Intent intent) {
		Logging.log("onNewIntent " + intent);
		super.onNewIntent(intent);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.app, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_filter_all_app:
			mAppLoader.setFlag(AppLoader.FILTER_ALL_APPS);
			fillterApp(AppLoader.FILTER_ALL_APPS);
			break;
		case R.id.action_filter_system_app:
			mAppLoader.setFlag(AppLoader.FILTER_SYSTEMS_APPS);
			fillterApp(AppLoader.FILTER_SYSTEMS_APPS);
			break;
		case R.id.action_filter_user_app:
			mAppLoader.setFlag(AppLoader.FILTER_USER_APPS);
			fillterApp(AppLoader.FILTER_USER_APPS);
			break;
		default:
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onInnerClickLisener(View view, final int position) {
		PopupMenu popupMenu = new PopupMenu(AppActivity.this, view);
		popupMenu.inflate(R.menu.app_action);
		if (isRoot) {
			if (mApplicationInfos.get(position).isSystemApp) {
				popupMenu.getMenu().add(0, MENU_ACTION_CONVERT_2_USER, 4,
						R.string.convert_to_user);
			} else {
				popupMenu.getMenu().add(0, MENU_ACTION_CONVERT_2_SYSTEM, 4,
						R.string.convert_to_system);
			}
		}

		popupMenu.setOnMenuItemClickListener(new OnMenuItemClickListener() {

			@Override
			public boolean onMenuItemClick(MenuItem arg0) {
				switch (arg0.getItemId()) {
				case R.id.action_launch:
					AppUtils.launchApp(getApplicationContext(),
							mApplicationInfos.get(position).pgk);
					break;
				case R.id.action_property:
					AppUtils.showPackageDetail(AppActivity.this,
							mApplicationInfos.get(position).pgk);
					break;
				case R.id.action_uninstall:
					AppUtils.uninstallApp(getApplicationContext(),
							mApplicationInfos.get(position).pgk);
					break;
				case MENU_ACTION_CONVERT_2_SYSTEM:
					convertApp(mApplicationInfos.get(position));
					break;
				case MENU_ACTION_CONVERT_2_USER:
					convertApp(mApplicationInfos.get(position));
					break;
				default:
					break;
				}
				return false;
			}

		});
		popupMenu.show();

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if (isPickApp) {
			AppInfo info = mApplicationInfos.get(position);
			info.position = appPosition;
			DBHelper.getInstance(getApplicationContext()).insertFavorite(
					getApplicationContext(), info);
			Broadcast.sendBroadcast(getApplicationContext(),
					CONFIG.BROADCAST.ACTION_FAVORITE_APP_CHANGED);
			finish();
			return;
		}
		AppUtils.launchApp(getApplicationContext(),
				mApplicationInfos.get(position).pgk);

	}

	private void convertApp(final AppInfo appInfo) {
		new AsyncTask<Void, Void, String>() {

			@Override
			protected String doInBackground(Void... params) {
				if (!isRoot) {
					return AppActivity.this.getResources().getString(
							R.string.root_require);
				}
				if (!RootTools.isBusyboxAvailable()) {
					return AppActivity.this.getResources().getString(
							R.string.busybox_not_available);
				}

				boolean copy = RootTools.copyFile(appInfo.srcDir,
						appInfo.isSystemApp ? USER_APP_PATH : SYSTEM_APP_PATH,
						true, true);
				if (!copy) {
					return AppActivity.this.getResources().getString(
							R.string.please_try_again_later);

				}
				RootTools.deleteFileOrDirectory(appInfo.srcDir, true);
				return null;
			}

			@Override
			protected void onPostExecute(String result) {
				if (result != null) {
					Toast.makeText(AppActivity.this, result, Toast.LENGTH_LONG)
							.show();
					return;
				}
				showRestartDialog();
				super.onPostExecute(result);
			}
		}.execute();

	}

	private void showRestartDialog() {
		DialogFragment dialogFragment = new DialogFragment() {
			@Override
			public View onCreateView(LayoutInflater inflater,
					ViewGroup container, Bundle savedInstanceState) {
				View rootView = inflater.inflate(R.layout.view_dialog_common0,
						container, false);
				final TextView timer = (TextView) rootView
						.findViewWithTag(getString(R.string.tag_text));
				CountDownTimer countDownTimer = new CountDownTimer(5000, 1000) {

					@Override
					public void onTick(long millisUntilFinished) {
						timer.setText((millisUntilFinished) / 1000 + " (s)");

					}

					@Override
					public void onFinish() {
						timer.setText("0 (s)");
						RootTools.restartAndroid();

					}
				};
				countDownTimer.start();

				return rootView;
			}

			@Override
			public Dialog onCreateDialog(Bundle savedInstanceState) {
				Dialog dialog = super.onCreateDialog(savedInstanceState);
				dialog.setTitle(getString(R.string.restart));
				return dialog;
			}
		};
		dialogFragment.show(getSupportFragmentManager(), null);
	}

	@Override
	public Loader<List<AppInfo>> onCreateLoader(int arg0, Bundle arg1) {
		mPullToRefreshLayout.setRefreshing(true);
		return mAppLoader = new AppLoader(getApplicationContext()) {
			@Override
			protected void onStartLoading() {
				super.onStartLoading();
			}

			@Override
			public void onContentChanged() {
				mPullToRefreshLayout.setRefreshing(true);
				super.onContentChanged();
			}

		};
	}

	@Override
	public void onLoadFinished(Loader<List<AppInfo>> arg0, List<AppInfo> arg1) {
		mOriginalAppInfos = arg1;
		mApplicationInfos.clear();
		mApplicationInfos.addAll(arg1);
		mAppAdapter.notifyDataSetChanged();
		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				mPullToRefreshLayout.setRefreshComplete();
			}
		}, 2000);
	}

	@Override
	public void onLoaderReset(Loader<List<AppInfo>> arg0) {

	}

	private void fillterApp(int flag) {
		List<AppInfo> filterApp = new ArrayList<AppInfo>();
		if (flag == AppLoader.FILTER_ALL_APPS) {
			filterApp.addAll(mOriginalAppInfos);
		} else if (flag == AppLoader.FILTER_USER_APPS) {
			for (AppInfo appInfo : mOriginalAppInfos) {
				if (!appInfo.isSystemApp) {
					filterApp.add(appInfo);
				}
			}
		} else if (flag == AppLoader.FILTER_SYSTEMS_APPS) {
			for (AppInfo appInfo : mOriginalAppInfos) {
				if (appInfo.isSystemApp) {
					filterApp.add(appInfo);
				}
			}
		}
		mApplicationInfos.clear();
		mApplicationInfos.addAll(filterApp);
		mAppAdapter.notifyDataSetChanged();
	}

	@Override
	public void onRefreshStarted(View view) {
		if (mAppLoader != null) {
			mAppLoader.onContentChanged();
		}

	}
}
